<template>
  <div class="ai-assistant">
    <!-- 居中 -->
    <div ref="aiAssistantEdgeCenter" v-if="iconPosition === 'center'" class="ai-assistant-edge-center">
      <div
        class="ai-assistant-edge-center-icon"
        :class="isIconMouse ? '' : 'hover_head_circle'"
        @mouseenter="onMouseEnterIcon"
        @mouseleave="onMoreleaveIcon"
        @mousedown="handleMouseDown($event),closeRightClickMenu()"
        @click="onOpenAiChat"
        @contextmenu="onRightClick"
        :style="{ backgroundImage: `url(${currentCenterIcon})` }"
      >
      </div>
    </div>

    <!-- 右边 -->
    <div v-else-if="iconPosition === 'right'" class="ai-assistant-edge-tip-right">
      <img
        @mousedown="handleMouseDown"
        @dblclick="openAiChat"
        :src="currentRightIcon"
        width="30"
        draggable="false"
      ></img>
    </div>
    <!-- 左边 -->
    <div v-else-if="iconPosition === 'left'" class="ai-assistant-edge-tip-left">
      <img
        @mousedown="handleMouseDown"
        @dblclick="openAiChat"
        :src="currentLeftIcon"
        width="30"
        draggable="false"
      ></img>
    </div>
    <!-- 底部 -->
    <div v-else-if="iconPosition === 'bottom'" class="ai-assistant-edge-tip-bottom">
      <img
        @mousedown="handleMouseDown"
        @dblclick="openAiChat"
        :src="currentBottomIcon"
        width="55"
        draggable="false"
      ></img>
    </div>
    <!-- 顶部 -->
    <div v-else-if="iconPosition === 'top'" class="ai-assistant-edge-tip-top">
      <img
        @mousedown="handleMouseDown"
        @dblclick="openAiChat"
        :src="currentTopIcon"
        width="55"
        draggable="false"
      ></img>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import useWindowDrag from '@/hooks/useMouseDown'
import ipcMainApi from '@/ipcMainApi'
import { reportEvent } from '@/utils/aegis';

let { handleMouseDown, isKeyDown, isDragging } = useWindowDrag('aiIcon-window')

// 图标路径（根据你实际资源路径调整）
const currentCenterIcon = ref(new URL('@/assets/image/aiAssistant/currentCenter.png', import.meta.url).href)
const currentRightIcon = ref(new URL('@/assets/image/aiAssistant/currentRight.png', import.meta.url).href)
const currentLeftIcon = ref(new URL('@/assets/image/aiAssistant/currentLeft.png', import.meta.url).href)
const currentBottomIcon = ref(new URL('@/assets/image/aiAssistant/currentBottom.png', import.meta.url).href)
const currentTopIcon = ref(new URL('@/assets/image/aiAssistant/currentTop.png', import.meta.url).href)

const winPosition = ref() // 窗口位置
let iconPosition = ref('center') // 图标位置
const isIconMouse = ref(false) // 图标呼吸效果
const isIntranet = ref(false) // 当前网络是否是内网

// 单击打开ai聊天窗口
const onOpenAiChat = () => {
  if (!isDragging.value) openAiChat()
}
// 打开聊天窗口
const openAiChat = async () => {
  isIntranet.value = await ipcMainApi.publicApi.getIsIntranet()
  if (isIntranet.value) {
    ipcMainApi.aiAssistantApi.hideMoreFeatures(300)
    // ipcMainApi.aiAssistantApi.openAiChat()
    ipcMainApi.browserViewApi.showBrowserView()
    initialState()
    // 上报打开ai窗口事件
    reportEvent('openAiChat');
  }
}

// 右键菜单
const onRightClick = (event) => {
  event.preventDefault();
  ipcMainApi.aiAssistantApi.showRightClickMenu()

  initialState()
  initDiscussionGroup()
}

// 关闭右键菜单
const closeRightClickMenu = () => {
  ipcMainApi.aiAssistantApi.hideRightClickMenu()
}

// 初始化状态
const initialState = () => {
  isIconMouse.value = false
}

// 初始化交流群
const initDiscussionGroup = () => {
  clearTimeout(discussionGroupTimeout.value)
  discussionGroupTimeout.value = null
  isDiscussionGroup.value = false
}

// 交流群
const isDiscussionGroup = ref(false)
const discussionGroupTimeout = ref()

// 鼠标移入icon
const onMouseEnterIcon = () => {
  if (!isKeyDown.value) {
    ipcMainApi.aiAssistantApi.showMoreFeatures()
    if (!isDiscussionGroup.value) {
      isIconMouse.value = true
      discussionGroupTimeout.value = setTimeout(() => {
        isDiscussionGroup.value = true
        initialState()
        ipcMainApi.aiAssistantApi.createDiscussionGroup()
      }, 2500)
    }
  }
}
// 鼠标移出icon
const onMoreleaveIcon = () => {
  initialState()
  initDiscussionGroup()
}

watch(isKeyDown, (newVal) => {
  if (newVal) {
    ipcMainApi.aiAssistantApi.hideMoreFeatures(0)
    ipcMainApi.aiAssistantApi.destroyDiscussionGroup()
    initDiscussionGroup()
    initialState()
  }
})


const intervalPot = ref() // 定时器id
const aiAssistantEdgeCenter = ref() // 获取元素位置
onMounted(async () => {
  window.electron.ipcRenderer.on('destroy-discussion-group', (_event) => { // 隐藏加入讨论组
    isDiscussionGroup.value = false
  })
  window.electron.ipcRenderer.on('create-discussion-group', (_event) => { // 显示加入讨论组
    isDiscussionGroup.value = true
  })
  window.electron.ipcRenderer.on('aiicon-window-blur', (_event) => { // 窗口失去焦点
    initialState()
  })
  window.electron.ipcRenderer.on('window-position-updated', (_event, data) => { // 窗口位置更新
    winPosition.value = data
    if (data.x === data.mouseRange.minX) {
      iconPosition.value = 'left'
    } else if (data.x + data.winW === data.mouseRange.maxX) {
      iconPosition.value = 'right'
    } else {
      if (data.y === data.mouseRange.minY) {
        iconPosition.value = 'top'
      } else if (data.y + data.winH === data.mouseRange.maxY) {
        iconPosition.value = 'bottom'
      } else {
        iconPosition.value = 'center'
      }
    }
  })

  intervalPot.value = setInterval(async() => {
    if (iconPosition.value === 'center') {
      const pot = await ipcMainApi.publicApi.getCursorScreenPoint() // 获取鼠标位置
      const bounds = aiAssistantEdgeCenter.value.getBoundingClientRect() // 获取元素位置
      const winX = window.screenX + (window.innerWidth - bounds.width) / 2
      const winY = window.screenY + (window.innerHeight - bounds.height) / 2
      const inside = (pot.x >= winX && pot.x <= winX + bounds.width && pot.y >= winY && pot.y <= winY + bounds.height);
      if (!inside) initialState()
    }
  }, 1000)

  // 注册快捷键
  const settings = await ipcMainApi.settingsApi.getSettings()
  const keys = [
    'evokeChortcut',
    'screenshotChortcut',
    'screenRecordingChortcut',
    'chatChortcut'
  ]
  if (settings?.shortcuts) {
    for (const key in settings?.shortcuts) {
      if (settings?.shortcuts[key] && keys.includes(key)) {
        ipcMainApi.settingsApi.saveSingleShortcut({ key, accelerator: settings?.shortcuts[key] })
      }
    }
  }
})
onUnmounted(() => {
  clearInterval(intervalPot.value)
  intervalPot.value = null
})
</script>

<style lang="scss" scoped>
.ai-assistant {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  user-select: none; /* 不允许鼠标复制 */
  // background-color: red;
  .ai-assistant-edge-center,
  .ai-assistant-edge-tip-right,
  .ai-assistant-edge-tip-left,
  .ai-assistant-edge-tip-bottom,
  .ai-assistant-edge-tip-top {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
  .ai-assistant-edge-center {
    .ai-assistant-edge-center-icon {
      cursor: pointer;
      width: 60px;
      height: 60px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 200;
      background-size: auto 60px;
      background-repeat: no-repeat;
      background-position: center;
    }
  }
  // 贴边
  .ai-assistant-edge-tip-right,
  .ai-assistant-edge-tip-left,
  .ai-assistant-edge-tip-bottom,
  .ai-assistant-edge-tip-top {
    img {
      cursor: pointer;
      position: absolute;
      transition: all 0.3s ease-in-out;
    }
  }
  .ai-assistant-edge-tip-right,
  .ai-assistant-edge-tip-left {
    img {
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .ai-assistant-edge-tip-left {
    img {
      left: -8px;
      &:hover {
        left: 0px;
      }
    }
  }
  .ai-assistant-edge-tip-right {
    img {
      right: -8px;
      &:hover {
        right: 0px;
      }
    }
  }
  .ai-assistant-edge-tip-bottom,
  .ai-assistant-edge-tip-top {
    img {
      left: 50%;
      transform: translateX(-50%);
    }
  }
  .ai-assistant-edge-tip-bottom {
    img {
      bottom: -12px;
      &:hover {
        bottom: 0px;
      }
    }
  }
  .ai-assistant-edge-tip-top {
    img {
      top: -12px;
      &:hover {
        top: 0px;
      }
    }
  }
  // 头像呼吸动效
  .hover_head_circle {
    position: relative;
    &:after {
      position: absolute;
      content: '';
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border-radius: 50%;
      width: 0px;
      height: 0px;
      box-shadow: inset 0 0 20px rgba(255, 255, 255);
      animation: afterBreathWave 2s infinite;
    }
  }
  // 头像呼吸动效动画
  @keyframes afterBreathWave {
    0% {
      width: 50px;
      height: 50px;
      opacity: 1;
    }
    100% {
      width: 60px;
      height: 60px;
      opacity: 0;
    }
  }
}
</style>
